package com.xinyue.network.message.stream;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

public abstract class AbstractMessageHeader implements IMessageHeader {
	// 消息ID
	private int messageId;
	// 消息创建时间
	private long sendTime;
	// 消息序列ID
	private int messageSeqId;
	// 版本号
	private int version;

	// 消息总大小
	private int messageSize;
	// 包头长度
	private int headerByteSize;

	public AbstractMessageHeader() {
		int size = 20;//此对象包头写的字节数
		this.addHeaderLength(size);
	}

	protected void addHeaderLength(int length) {
		this.headerByteSize += length;
	}

	public static int readMessageId(ByteBuf byteBuf) {
		byteBuf.markReaderIndex();
		byteBuf.skipBytes(8);
		int messageId = byteBuf.readInt();
		byteBuf.resetReaderIndex();
		return messageId;
	}

	@Override
	public void read(ByteBuf byteBuf) {
		messageSize = byteBuf.readInt();
		messageSeqId = byteBuf.readInt();
		messageId = byteBuf.readInt();
		sendTime = byteBuf.readLong();
		version = byteBuf.readInt();
	}

	@Override
	public ByteBuf write() {
		ByteBuf byteBuf = Unpooled.buffer(this.headerByteSize);
		byteBuf.writeInt(this.messageSeqId);
		byteBuf.writeInt(this.messageId);
		if (this.sendTime == 0) {
			this.sendTime = System.currentTimeMillis();
		}
		byteBuf.writeLong(this.sendTime);
		byteBuf.writeInt(this.version);
		return byteBuf;
	}

	@Override
	public void setMessageId(int messageId) {
		this.messageId = messageId;
	}

	public long getSendTime() {
		return sendTime;
	}

	public void setSendTime(long sendTime) {
		this.sendTime = sendTime;
	}

	public void setMessageSeqId(int messageSeqId) {
		this.messageSeqId = messageSeqId;
	}

	public void setMessageSize(int messageSize) {
		this.messageSize = messageSize;
	}
	public void setVersion(int version) {
		this.version = version;
	}

	public void setHeaderLength(int headerLength) {
		this.headerByteSize = headerLength;
	}

	@Override
	public int getMessageId() {
		return messageId;
	}

	@Override
	public int getMessageSeqId() {
		return messageSeqId;
	}

	public int getMessageSize() {
		return messageSize;
	}

	public int getVersion() {
		return version;
	}

	public int getHeaderLength() {
		return headerByteSize;
	}

	@Override
	public int getHeaderByteSize() {
		return headerByteSize;
	}
}
